package com.jiaeda.springsecurity.validate.code;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * Created by chengchaopeng on 2018/7/10.
 */
@RestController
public class ValidateCodeController {

    public static final  String SESSION_KEY="SESSION_KEY_IMAGE_CODE";

    /**
     * 操作session的工具类
     */
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    private ValidateCodeGenerator validateCodeGenerator;
    
    @GetMapping("/validate/code")
    public void simpleCodeImage(HttpServletRequest request, HttpServletResponse response)
     throws IOException {
        ValidateCode validateCode=validateCodeGenerator.generate(request);
        sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,validateCode);
        ImageIO.write(validateCode.getImage(),"JPEG",response.getOutputStream());
    }


}
